define(
		[],
		function() {
			function initStrut(defTpl) {

			};

			function loadScript(res, defTpl) {
				// 处理脚本加载
				var jsRegex = /.*(\.js)$/;
				var jspRegex = /.*(\.jsp)$/;
				if (res.scriptPath) {
					if (res.scriptPath.match(jsRegex)) {
						$.ajax({
							async : false,
							cache : false,
							dataType : "script",
							type : "GET",
							url : root + res.scriptPath
						});
					} else if (res.scriptPath.match(jspRegex)) {
						$.ajax({
							async : false,
							cache : false,
							dataType : "html",
							success : function(data) {
								defTpl._$script.html(data);
							},
							type : "GET",
							url : root + res.scriptPath
						});
					}
				}
			};
			
			function parserSearchColCtr(col) {
		        var cols = [];
		        if (col.controlType == 1) {
		            var c = {
		                ctr: '<div class="form-group">'
		                + '<label>'
		                + col.viewName
		                + '</label>'
		                + '<input type="text" class="form-control" name="'
		                + getColName(col) + '" ></div>'

		            }
		            cols.push(c);

		        } else if (col.controlType == 2) {
		            var c = {
		                ctr: $('<div class="form-group" style="position: relative;">'
		                + '<label>'
		                + col.viewName
		                + '</label>'
		                + '<input type="text" class="form-control" name="'
		                + getColName(col)
		                + '" data-am-datepicker></div>'),
		                onAfterAppend: function() {
		                    var div = this.ctr;
		                    div.find("input").datetimepicker({
		                        format: 'YYYY-MM-DD',
		                        locale: "zh-cn"

		                    });
		                }
		            }
		            cols.push(c);

		            if (col.conditionType == 11) {
		                c = {
		                    ctr: $('<div class="form-group" style="position: relative;">'
		                    + '<label>至</label>'
		                    + '<input type="text" class="form-control" name="'
		                    + getColName(col)
		                    + '_E"></div>'),
		                    onAfterAppend: function() {
		                        var div = this.ctr;
		                        div.find("input").datetimepicker({
		                            format: 'YYYY-MM-DD',
		                            locale: "zh-cn"

		                        });

		                    }

		                }
		                cols.push(c);

		            }


		        } else if (col.controlType == 3) {
		            var c = {
		                ctr: $('<div class="form-group" style="position: relative;">'
		                + '<label>'
		                + col.viewName
		                + '</label>'
		                + '<input type="text" class="form-control" name="'
		                + getColName(col)+ '"></div>'),
		                onAfterAppend: function() {
		                    var div = this.ctr;
		                    div.find("input").datetimepicker({
		                        format: 'YYYY-MM-DD HH:mm',
		                        locale: "zh-cn"

		                    });

		                }

		            }
		            cols.push(c);

		            if (col.conditionType == 11) {
		                var c = {
		                    ctr: $('<div class="form-group" style="position: relative;">'
		                    + '<label>至</label>'
		                    + '<input type="text" class="form-control" name="'
		                    + getColName(col)
		                    + '_e" data-am-datepicker ></div>'),
		                    onAfterAppend: function() {
		                        var div = this.ctr;
		                        div.find("input").datetimepicker({
		                            format: 'YYYY-MM-DD HH:mm',
		                            locale: "zh-cn"

		                        });

		                    }

		                }
		                cols.push(c);

		            }

		        } else if (col.controlType == 4) {
		            var html = '<div class="form-group">' + '<label>'
		            + col.viewName + '</label>'
		            + '<select  class="form-control" name="'
		            + getColName(col) + '" >';
		            html += '<option value=""></option>';
		            var items = webUtils.getDataDicItems(col.controlScript);
		            $.each(items, 
		            function(i, n) {
		                html += '<option value="' + n.value + '">' + n.name
		                + '</option>';

		            });

		            html = html + '</select>' + '</div>';
		            var c = {
		                ctr: $(html),
		                onAfterAppend: function() {
		                    var div = this.ctr;
		                    div.find("input").datetimepicker({
		                        format: 'YYYY-MM-DD HH:mm',
		                        locale: "zh-cn"

		                    });

		                }

		            }
		            cols.push(c);

		        }

		        return cols

		        function getColName(col) {
		            return col.name;

		        }

		    }

			var queryDefTpl = function(params) {
				var uuid = webUtils.uuid;
				var me = this;
				this.params = $.extend({
					code : "",// 查询定义的编码
					modelCode:"",//数据模型编码
					scriptDiv : "",// 引用脚本的div
					searchDiv : "",// 查询定义栏
					toolBarDiv : "",// 工具栏
					treeDiv : "",// tree表格
					treeCfg : {},// tree的配置信息，可以覆盖原配置
					model : 'serverEdit',// 'select'选择模型,'servierMix'混合模式,'serverEdit'服务编辑模式,'clientEdit'客户端编辑模式
					selectModel : 'multi',// single单选,multi多选
					winId : "",
					enableDrap:true,
					queryDatas : {},
					displayName:'TITLE',//显示的字段名
					root:{
						TITLE:'业务数据',
						ID: "-1",
		                isParent: true,
		                open: true
					},//根节点配置
					onSelect : function(row) {

					},
					onBeforeLoad : function(gridDef, grid) {
						return true;
					}
				}, params);
				
				
				
				this._$script = this.params.scriptDiv ? $(this.params.scriptDiv) : null;
		        this._$search = this.params.searchDiv ? $(this.params.searchDiv) : null;
				
				if(!me.params.modelCode){
					me.params.modelCode=me.params.code;
				}
				
				$.ajax({
		        	async: false,
		            data: {
		                code: this.params.code,
		                withStruts: true
		            },
		            dataType: "json",
		            type: "GET",
		            url: ctx + "/queryDefAction/findQueryDefByCode.do",
		            success: function(res) {
		            	// --------------------------加载脚本
		                loadScript(res, me);
		                // --------------------------加载按钮
		                var defalutOptBtns = [];
		                var inGridOptBtns = [];
		                if (res.optBtns) {
		                    $.each(res.optBtns, function(i, n) {
		                        if (webUtils.hasAllPermissions(n.optAuthCode)) {
		                            defalutOptBtns.push(n);
		                        }

		                    });

		                }
		                var toolbar = $(me.params.toolBarDiv);
		                if (toolbar.size() > 0) {

		                    if (defalutOptBtns
		                    && $.inArray(me.params.model, [
		                    'serverEdit', 'clientEdit', 
		                    'servierMix']) > -1) {
		                        // 处理按钮
		                        $
		                        .each(
		                        defalutOptBtns, 
		                        function(i, n) {
		                            var btn = $('<a class="btn btn-sm '
		                            + (n.btnCls ? n.btnCls
		                            : "btn-default")
		                            + ' am-margin-left-xs" title="'
		                            + n.title
		                            + '">'
		                            + (n.iconCls ? '<span class="'
		                            + n.iconCls
		                            + '"></span> '
		                            : '')
		                            + (!n.notDisplayTitle ? n.title
		                            : "")
		                            + '</a>');
		                            btn.click(function() {
		                                if (n.exeScript) {
		                                	var nodes = me.treeTpl.getSelectedNodes();
		                                    var t = eval("(function _t(treeTpl,nodes,queryDefTpl){"
		                                    + n.exeScript
		                                    + "(treeTpl,nodes,queryDefTpl);})");
		                                    var v = t.call(null,me.treeTpl,nodes,me);
		                                }
		                            });
		                            toolbar.append(btn);

		                        });
		                    }
		                    if ($.inArray(me.params.model, ['select', 
		                    'servierMix']) > -1) {
		                        var btn = $('<a class="btn btn-primary am-margin-left-xs">'
		                        + '<span class="glyphicon glyphicon-ok aria-hidden="true"></span> 选择'
		                        + '</a>');
		                        btn
		                        .click(function() {
		                            var rows = me.grid.rows({
		                                selected: true

		                            }).data();
		                            if (rows && rows.length > 0) {
		                                if (me.params.winId) {
		                                    webUtils
		                                    .topicPublish(
		                                    "queryData.selected."
		                                    + me.params.winId, 
		                                    rows);

		                                }

		                            } else {
		                                webUtils
		                                .alert("请勾选需要的数据");

		                            }

		                        });
		                        toolbar.append(btn);

		                    }

		                }
		                
		                if (res.searchColumns && me._$search) {
		                    // 处理搜索工具条
		                    $.each(res.searchColumns, function(i, n) {
		                        if (n.canView == 1) {
		                            var controls = parserSearchColCtr(n);
		                            $.each(controls, function(ctr_i, ctr_n) {
		                                me._$search.append(ctr_n.ctr);
		                                if (ctr_n.onAfterAppend) {
		                                    ctr_n.onAfterAppend.call(ctr_n);
		                                }
		                            });
		                        }
		                    });

		                    
		                    var searhcBt = $('<button type="button" class="am-margin-left-xs btn btn-primary">搜索</button>');
		                    me._$search.append(searhcBt);
		                    searhcBt.click(function() {
		                    	var datas=webUtils.formToObj(me._$search);
		                    	me.search(datas);
		                    	if(searchDialog){
		                    		searchDialog.close();
		                    	}
		                    });
		                    
		                    me._$search.append($('<div class="searchBtBar"></div>').append(searhcBt));
		                    me._$search.append('<div style="clear:both"></div>');
		                    
		                    if (toolbar.size() > 0 &&  me.params.searchBarType=='dialog') {
		                    	var btn = $('<a class="btn btn-sm btn-default am-margin-left-xs">' + '<span class="glyphicon glyphicon-search"></span> 搜索' + '</a>');
		                        
		                    	btn.click(function() {
		                        	searchDialog=webUtils.dialog({
		                        		type: 1,
		                        		dom:$(me.params.searchDiv)
		                        	});
		                        });
		                        
		                        toolbar.prepend(btn);
		                    }
		                }
		                
		            }
		        });
				
				this.search=function(datas){
					var searchData = JSON.stringify(datas);
					me.treeTpl.setting.async.otherParam.searchData = searchData;
                	me.treeTpl.reAsyncChildNodes(me.treeTpl.getNodesByParam("ID", "-1")[0], "refresh");
				}
				
				this.root = $.extend({
	                ID: "-1",
	                isParent: true,
	                open: true
				},me.params.root);
				
				this.treeTpl = $.fn.zTree.init($(me.params.treeDiv), {
					async: {
		                enable: true,
		                url: ctx + "/queryDefAction/queryTreeDatas.do",
		                autoParam: ["ID=PID"],
		                otherParam:{"code":me.params.code},
		                dataFilter: function (treeId, parentNode, responseData) {
		                    if (responseData) {
		                        $.each(responseData, function (i, n) {
		                            if (n.childrenSize > 0) {
		                                n.isParent = true;
		                            }
		                        });
		                    }
		                    return responseData;
		                }
		            },
		            data: {
		                key: {
		                    name: me.params.displayName
		                }
		            },
		            edit: {
		                enable: me.params.enableDrap,
		                showRemoveBtn: false,
		                showRenameBtn: false,
		                drag: {
		                    isCopy: false
		                }
		            },
		            callback: {
		            	beforeDrag:function(treeId,treeNodes){
		            		if(treeId=='-1'){
		            			return false;
		            		}else{
		            			return true;
		            		}
		            	},
		                onDrop: function (e, treeId, treeNodes, targetNode, moveType, isCopy) {
		                    if (treeNodes && treeNodes.length > 0) {
		                        var treeNode = treeNodes[0];
		                        var pNode = me.treeTpl.getNodeByTId(treeNode.parentTId);
		                        var ids = [];
		                        $.each(pNode.children, function (i, n) {
		                            ids.push(n.id);
		                        });
		                        
		                        $.post(ctx + "/formDataAction/seqTreeNodes.do", {ids: ids.join(","), pid: pNode.id,code:me.params.modelCode}, function (data) {
		                            if (data.success) {
		                            } else {
		                                webUtils.error(data.msg);
		                            }
		                        }, "json");
		                        
		                    }
		                },
		                onClick: function (e, treeId, treeNode, clickFlag) {
		                	if (clickFlag != 0) {
		                		me.params.onSelect.call(null,treeNode);
		                	}
		                }
		            }
				}, this.root);
				
				this.treeTpl.reAsyncChildNodes(this.treeTpl.getNodesByParam("ID", "-1")[0], "refresh");
			}
			
			

			return queryDefTpl;
		});